package com.ytf.core.exception;

import com.ytf.core.common.Resp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 捕获 BusinessException
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<Resp<Void>> handleBusinessException(BusinessException e) {
        logger.error("业务异常：{}", e.getMsg(), e);
        // 返回自定义的错误响应
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(Resp.error(e.getCode(), e.getMsg()));
    }

    // 捕获其他未处理的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Resp<Void>> handleException(Exception e) {
        logger.error("系统异常：{}", e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Resp.error(500, "系统内部错误：" + e.getMessage()));
    }
}
